﻿
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
using System.Data;
namespace HZ.DrugTrade.Web.Hospitals.SalesReturn
{
    public partial class RetrunGoodsOderUpdate : BasePage
    {
        public RetrunGoodsOderUpdate()
        {
            this.ModuleNo = Module.退货单管理.ToString();
        }
        public string ReturnPlanname = "";//退货单名称
        public string pReturnSerialID = "";//退货单编号
        IBLL_Purchase IBLLP = Factory.BLL_Purchase();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }

            ReturnPlanname = Request.QueryString["TINN"];//ReturnPlanname退货单名字
            pReturnSerialID = Request.QueryString["TIDN"];//ReturnSerialID退货单ID
            ViewState["status"] = Request.QueryString["TST"];
            if (!Page.IsPostBack)
            {
                BindReturnGoodList();
                int totalCount = 0;
                IList<HZ.DrugTrade.Model.View.ReturnMerchandise> ReturnMerchandiselist = IBLLP.GetReturnReturnMerchandisewhere(pReturnSerialID, 1, 0, out totalCount);
                if (ReturnMerchandiselist.Count == 0)
                {
                    PageError("退货单不存在！", "ReturnGoodsOderListUnSubmit.aspx");
                }
                if (new HZ.Common.ConvertHelper(Request.QueryString["TST"]).String != "")
                {
                    btnAdd.Visible = Request.QueryString["TST"].ToString() == "1";
                    btnSave.Visible = Request.QueryString["TST"].ToString() == "1";
                    btnDel.Visible = Request.QueryString["TST"].ToString() == "1";
                    btnSubmit.Visible = Request.QueryString["TST"].ToString() == "1";
                    //将最后一列（复选框列）隐藏掉
                    gvwReturngoods.Columns[gvwReturngoods.Columns.Count - 1].Visible = Request.QueryString["TST"].ToString() == "1";
                }
            }
        }
        /// <summary>
        /// 绑定退货商品列表
        /// </summary>
        private void BindReturnGoodList()
        {
            HZ.DrugTrade.Model.Query.ReturnMerchandiseDetail aReturnMerchandiseDetail = new HZ.DrugTrade.Model.Query.ReturnMerchandiseDetail();
            aReturnMerchandiseDetail.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            aReturnMerchandiseDetail.GoodsName = txtGoodsName.Text;
            aReturnMerchandiseDetail.Outlookc = txtOutLookc.Text;
            aReturnMerchandiseDetail.PinyinCode = this.txtpinyincode.Text.Trim();
            aReturnMerchandiseDetail.Material = txtMaterial.Text;
            //aReturnMerchandiseDetail.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                aReturnMerchandiseDetail.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                aReturnMerchandiseDetail.ProjectID = "0001";
            }
            aReturnMerchandiseDetail.CompanyName = txtCompanyName_PS.Text;
            aReturnMerchandiseDetail.CompanyName_SC = txtCompanyname_sc.Text;
            aReturnMerchandiseDetail.BatchRecordID = txtBatchRecordID.Text;
            aReturnMerchandiseDetail.ReturnTimeFrom = new HZ.Common.ConvertHelper(txtStartDate.Text).ToDateTime;
            aReturnMerchandiseDetail.ReturnTimeTo = new HZ.Common.ConvertHelper(txtEndDate.Text).ToDateTime;
            aReturnMerchandiseDetail.ReturnSerialID = Request.QueryString["TIDN"].ToString();

            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            gvwReturngoods.PageSize = AspNetPager1.PageSize;
            gvwReturngoods.DataSource = IBLLP.GetReturnReturnMerchandiseDetail(aReturnMerchandiseDetail, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            gvwReturngoods.DataBind();
            AspNetPager1.RecordCount = totalCount;
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BindReturnGoodList();
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindReturnGoodList();
        }

        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                //txtReturnName.Text = "";
                txtCompanyName_PS.Text = "";
                txtStartDate.Text = "";
                txtEndDate.Text = "";
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd1_Click(object sender, EventArgs e)
        {
            Response.Redirect("ReturnGoodsOrderCheck.aspx?TIDN=" + pReturnSerialID + "&TINN=" + HttpUtility.UrlEncode(ReturnPlanname));
        }

        /// <summary>
        /// 更新退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string nOrgID = CurrentAccount.GetUser().Org.OrgID;//医疗机构ID
            List<HZ.DrugTrade.Model.ReturnMerchandiseDetail> DistributionBatchRecordList = new List<HZ.DrugTrade.Model.ReturnMerchandiseDetail>();
            for (int i = 0; i < this.gvwReturngoods.Rows.Count; i++)
            {
                if (gvwReturngoods.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    if (((System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwReturngoods.Rows[i].FindControl("checkbox1")).Checked == true)
                    {
                        HZ.DrugTrade.Model.ReturnMerchandiseDetail aReturnMerchandise = new HZ.DrugTrade.Model.ReturnMerchandiseDetail();

                        //获得退货量
                        TextBox txtReturnnum = (TextBox)gvwReturngoods.Rows[i].FindControl("txtCount");

                        int? iReturnnum = new HZ.Common.ConvertHelper(txtReturnnum.Text.Trim()).ToInt32;

                        //获取入库总量和已退数量
                        int? nReturnCountSum = Convert.ToInt32(((Label)gvwReturngoods.Rows[i].FindControl("lblReturnCountSum")).Text.Trim());
                        int? nGwvStock = Convert.ToInt32(((Label)gvwReturngoods.Rows[i].FindControl("lblStock")).Text.Trim());

                        if (iReturnnum <= 0 || iReturnnum == null)
                        {
                            HZ.Web.WebUtil.Alert("请填写退货数量！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtCount")).Focus();
                            return;
                        }
                        //else if (iReturnnum + nReturnCountSum > nGwvStock) //Updated by sinodier 2011年1月16日7:22:54
                        else if (iReturnnum > nGwvStock)
                        {
                            HZ.Web.WebUtil.Alert("退货数量大于库存数量，请重新填写！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtCount")).Focus();
                            return;
                        }

                        //获得采购价格
                        TextBox txtPrice = (TextBox)gvwReturngoods.Rows[i].FindControl("txtPrice");

                        decimal? iPrice = new HZ.Common.ConvertHelper(txtPrice.Text.Trim()).ToDecimal;
                        if (iPrice == null || iPrice <= 0)
                        {
                            HZ.Web.WebUtil.Alert("请填写采购价格！", this);
                            ((TextBox)gvwReturngoods.Rows[i].FindControl("txtPrice")).Focus();
                            return;
                        }

                        aReturnMerchandise.RetrunPrice = iPrice;
                        //配送明细ID

                        aReturnMerchandise.ReturnCount = iReturnnum;
                        aReturnMerchandise.ReturnSerialDetailID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["ReturnSerialDetailID"].ToString()).String;
                        //aReturnMerchandise.RetrunPrice = Convert.ToDecimal(((Label)gvwReturngoods.Rows[i].FindControl("lblPrice")).Text.Trim());
                        aReturnMerchandise.CompanyID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["CompanyID"].ToString()).String;
                        aReturnMerchandise.ReturnSerialID = Request.QueryString["TIDN"];//ReturnSerialID退货单ID
                        DistributionBatchRecordList.Add(aReturnMerchandise);

                    }
                }
            }
            if (DistributionBatchRecordList.Count > 0)
            {
                IBLL_Purchase I_Purchase = Factory.BLL_Purchase();
                int nSuccess = 0;
                nSuccess = I_Purchase.UpdateReturnMerchandiseDetail_Batch_Hospital(DistributionBatchRecordList);

                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("保存成功", this);
                    BindReturnGoodList();
                }
                else if (nSuccess == 2)
                {
                    HZ.Web.WebUtil.Alert("退货单已提交！", this);
                    BindReturnGoodList();
                }
                else if (nSuccess == 3)
                {
                    HZ.Web.WebUtil.Alert("退货单明细已删除！", this);
                    BindReturnGoodList();
                }
                else if (nSuccess == 0)
                {
                    HZ.Web.WebUtil.Alert("保存失败", this);
                    BindReturnGoodList();
                }
            }
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd0_Click(object sender, EventArgs e)
        {
            IBLL_Purchase IBLLP = Factory.BLL_Purchase();
            string nOrgID = CurrentAccount.GetUser().Org.OrgID;//医疗机构ID
            List<HZ.DrugTrade.Model.ReturnMerchandiseDetail> DistributionBatchRecordList = new List<HZ.DrugTrade.Model.ReturnMerchandiseDetail>();
            for (int i = 0; i < this.gvwReturngoods.Rows.Count; i++)
            {
                if (gvwReturngoods.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    if (((System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwReturngoods.Rows[i].FindControl("checkbox1")).Checked == true)
                    {
                        HZ.DrugTrade.Model.ReturnMerchandiseDetail aReturnMerchandise = new HZ.DrugTrade.Model.ReturnMerchandiseDetail();

                        //配送明细ID
                        aReturnMerchandise.ReturnSerialDetailID = new HZ.Common.ConvertHelper(gvwReturngoods.DataKeys[i].Values["ReturnSerialDetailID"].ToString()).String;
                        DistributionBatchRecordList.Add(aReturnMerchandise);

                    }
                }
            }
            if (DistributionBatchRecordList.Count > 0)
            {
                IBLL_Purchase I_Purchase = Factory.BLL_Purchase();
                int nSuccess = 0;

                //删除
                nSuccess = I_Purchase.DeleteReturnMerchandiseDetail_Batch_Hospital(DistributionBatchRecordList);

                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("成功删除明细", this);
                    BindReturnGoodList();
                }
                else if (nSuccess == 2)
                {
                    HZ.Web.WebUtil.Alert("退货单已提交！", this);
                    BindReturnGoodList();
                }
                else if (nSuccess == 0)
                {
                    HZ.Web.WebUtil.Alert("删除失败", this);
                    BindReturnGoodList();
                }
            }
        }

        /// <summary>
        /// 提交退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd2_Click(object sender, EventArgs e)
        {
            if (gvwReturngoods.Rows.Count <= 0)
            {
                HZ.Web.WebUtil.Alert("退货明细为空，无法提交无法提交退货单！");
                return;

            }
            for (int i = 0; i < gvwReturngoods.Rows.Count; i++)
            {
                TextBox txtCount = (TextBox)gvwReturngoods.Rows[i].FindControl("txtCount");
                if (string.IsNullOrEmpty(txtCount.Text))
                {
                    HZ.Web.WebUtil.Alert("有退货数量为空的明细，无法提交退货单！", this);
                    txtCount.Focus();
                    return;
                }

            }
            List<HZ.DrugTrade.Model.ReturnMerchandise> DistributionBatchRecordList = new List<HZ.DrugTrade.Model.ReturnMerchandise>();
            Model.ReturnMerchandise aReturnmer = new ReturnMerchandise();
            aReturnmer.ReturnSerialID = Request.QueryString["TIDN"];//ReturnSerialID退货单ID
            DistributionBatchRecordList.Add(aReturnmer);
            int nSucess = 0;
            IBLL_Purchase I_Purchase = Factory.BLL_Purchase();
            nSucess = I_Purchase.SubmitReturnMerchandise_Batch_Hospital(DistributionBatchRecordList);
            if (nSucess == 1)
            {
                HZ.Web.WebUtil.Alert("操作成功", this);
                PageInfo("提交成功！", "ReturnGoodsOderList.aspx");

            }
            else if (nSucess == 2)
            {
                HZ.Web.WebUtil.Alert("有订单发票已开无法提交！", this);
            }
            else if (nSucess == 0)
            {
                HZ.Web.WebUtil.Alert("操作失败", this);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwReturngoods_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                TextBox txtCount = e.Row.FindControl("txtCount") as TextBox;
                Label lblCount = e.Row.FindControl("lblCount") as Label;

                TextBox txtPrice = e.Row.FindControl("txtPrice") as TextBox;
                Label lblPrice = e.Row.FindControl("lblPrice") as Label;

                if (Convert.ToString(ViewState["status"]) == "2")
                {
                    txtCount.Visible = false;
                    lblCount.Visible = true;

                    txtPrice.Visible = false;
                    lblPrice.Visible = true;
                }
                else
                {
                    txtCount.Visible = true;
                    lblCount.Visible = false;

                    txtPrice.Visible = false;
                    lblPrice.Visible = true;
                }
            }
        }

        /// <summary>
        /// 2009-11-26
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            IBLL_Purchase IBLLP = Factory.BLL_Purchase();
            HZ.DrugTrade.Model.Query.ReturnMerchandiseDetail aReturnMerchandiseDetail = new HZ.DrugTrade.Model.Query.ReturnMerchandiseDetail();
            aReturnMerchandiseDetail.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            aReturnMerchandiseDetail.ReturnSerialID = pReturnSerialID;
            aReturnMerchandiseDetail.GoodsName = txtGoodsName.Text;
            aReturnMerchandiseDetail.PinyinCode = this.txtpinyincode.Text.Trim();
            aReturnMerchandiseDetail.Outlookc = txtOutLookc.Text;
            aReturnMerchandiseDetail.Material = txtMaterial.Text;
            aReturnMerchandiseDetail.CompanyName = txtCompanyName_PS.Text;
            aReturnMerchandiseDetail.CompanyName_SC = txtCompanyname_sc.Text;
            aReturnMerchandiseDetail.BatchRecordID = txtBatchRecordID.Text;
            //aReturnMerchandiseDetail.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                aReturnMerchandiseDetail.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                aReturnMerchandiseDetail.ProjectID = "0001";
            }
            aReturnMerchandiseDetail.ReturnTimeFrom = new HZ.Common.ConvertHelper(txtStartDate.Text).ToDateTime;
            aReturnMerchandiseDetail.ReturnTimeTo = new HZ.Common.ConvertHelper(txtEndDate.Text).ToDateTime;
            int totalCount = 0;
            IList<Model.View.ReturnMerchandiseDetail> gvwReturnGoodsList = IBLLP.GetReturnReturnMerchandiseDetail(aReturnMerchandiseDetail, 1, 0, out totalCount);
            DataTable dt = HZ.Data.ModelConvert.GetDataTableFromModel(gvwReturnGoodsList);
            //执行导出
            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwReturngoods);
        }
    }
}
